package it.mbus.bz;

import it.mbus.component.UserComponent;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

import android.os.Bundle;
import android.os.Environment;
import android.app.Activity;
import android.content.Intent;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.ProgressBar;
import android.widget.Toast;

public class Starter extends Activity {


	public static boolean inizialize() throws IOException {
		// Create Folder
		File folder = new File(Environment.getExternalStorageDirectory()
				.toString() + "/mBus");
		folder.mkdirs();
		// Save the path as a string value
		String extStorageDirectory = folder.toString();

		// Create New file and name it logU.mbs
		File file = new File(extStorageDirectory, "logU.mbs");
		return file.createNewFile();

	}

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_starter);

		/***
		 * 1) controllo se ci sono dati nella memoria 
		 * 	a) se si: controllo i dati
		 * 		a1) dati validi: mando a HOME 
		 * 		a2) dati errati: mando a Log/Reg
		 * 	b) se no: crea la cartella mBus, e mando a Log/Reg
		 * 2) controllo connessione internet
		 * 3) controllo NFC
		 * 4) controllo GPS
		 **/
		

		try {
			if (inizialize()) { //inizializzo la memoria, cercando la cartella mBus
				
				// NON ESISTE
				Intent reg = new Intent(this, LogReg.class);
				startActivity(reg);
				finish();
			} else {
				// FILE GIA PRESENTE
				// prendo i dati, li verifico e mando alla activty giusta
				String dati= UserComponent.leggiDati().trim();
				if(dati.contains("!i!")){
				String dati2[] = dati.split("!i!");
				String u=dati2[0];
				String p=dati2[1];
				if(UserComponent.login(u, p)){
					Toast.makeText(getBaseContext(),
							"Utente Autenticato",
							Toast.LENGTH_SHORT).show();
					Intent reg = new Intent(this, Home.class); 
					startActivity(reg);
					finish();
				}
				else{
					Toast.makeText(getBaseContext(),
							"Errore nell accesso, Riprova!",
							Toast.LENGTH_SHORT).show();
					Intent reg = new Intent(this, Login.class);
					startActivity(reg);
					finish();
				}
				}
				else{
					
					Intent reg = new Intent(this, LogReg.class);
					startActivity(reg);
					finish();
				}
				
				
			}
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		//progressBar.setVisibility(View.GONE);


	}

}
